package com.xie.smfs.entity;

import net.minecraft.entity.EntityType;
import net.minecraft.entity.attribute.EntityAttributes;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.DamageType;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.util.Identifier;
import net.minecraft.world.World;

import java.util.Objects;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.minecraft.entity.attribute.DefaultAttributeContainer;
import net.minecraft.entity.LivingEntity;

public class JumpGhostEntity extends GhostEntity {
    private static final Logger LOGGER = LoggerFactory.getLogger(JumpGhostEntity.class);

    public static DefaultAttributeContainer.Builder createLivingAttributes() {
        return LivingEntity.createLivingAttributes()
                .add(EntityAttributes.GENERIC_MAX_HEALTH, 20.0)
                .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.25)
                .add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 5.0);
    }

    private static final boolean HAS_GHOST_DOMAIN = true;
    private static final int GHOST_DOMAIN_LEVEL = 0;
    private static final double GHOST_DOMAIN_RADIUS = 32.0;
    private static final char TERROR_LEVEL = 'C';

    private int jumpCooldown = 0;
    private int checkInterval = 0;

    // 存储每个玩家的跳跃状态
    private final Map<UUID, Boolean> playerPreviousOnGround = new HashMap<>();

    public JumpGhostEntity(EntityType<? extends GhostEntity> entityType, World world) {
        super(entityType, world, HAS_GHOST_DOMAIN, GHOST_DOMAIN_LEVEL, GHOST_DOMAIN_RADIUS, TERROR_LEVEL);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_MAX_HEALTH)).setBaseValue(20.0);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_MOVEMENT_SPEED)).setBaseValue(0.25);
        Objects.requireNonNull(this.getAttributeInstance(EntityAttributes.GENERIC_ATTACK_DAMAGE)).setBaseValue(5.0);
        this.attackCooldown = 20;
    }

    @Override
    protected boolean shouldAttackPlayer(PlayerEntity player) {
        if (jumpCooldown > 0) {
            jumpCooldown--;
            return false;
        }

        UUID playerId = player.getUuid();
        boolean isOnGround = player.isOnGround();
        double yVelocity = player.getVelocity().y;

        // 获取之前的接地状态
        boolean wasOnGround = playerPreviousOnGround.getOrDefault(playerId, true);

        // 检测跳跃：之前在地面，现在不在，且Y速度为正
        boolean justJumped = wasOnGround && !isOnGround && yVelocity > 0.1;

        // 更新状态
        playerPreviousOnGround.put(playerId, isOnGround);

        if (justJumped) {
            jumpCooldown = 20;
            return true;
        }

        return false;
    }

    @Override
    public void tick() {
        super.tick();

        // 每5秒记录一次详细状态
        if (this.age % 100 == 0) {
            // 获取世界中的所有玩家
            int playerCount = this.getWorld().getPlayers().size();
            int inRangeCount = 0;

            for (PlayerEntity player : this.getWorld().getPlayers()) {
                if (isInDetectionRange(player)) {
                    inRangeCount++;

                }
            }

        }

        // 定期清理不再范围内的玩家数据
        checkInterval++;
        if (checkInterval >= 200) { // 每10秒清理一次
            int initialSize = playerPreviousOnGround.size();
            checkInterval = 0;

            playerPreviousOnGround.keySet().removeIf(playerId -> {
                PlayerEntity player = this.getWorld().getPlayerByUuid(playerId);
                boolean shouldRemove = player == null || !player.isAlive() || !isInDetectionRange(player);
                if (shouldRemove) {
                        }
                return shouldRemove;
            });

        }
    }

    // 检查玩家是否在检测范围内
    private boolean isInDetectionRange(PlayerEntity player) {
        double distanceSquared = this.squaredDistanceTo(player);
        boolean inRange = distanceSquared <= GHOST_DOMAIN_RADIUS * GHOST_DOMAIN_RADIUS; // 使用鬼域半径作为检测范围
        return inRange;
    }

    @Override
    protected void executeAttack(PlayerEntity player) {
        // 瞬移到玩家面前
        this.teleport(player.getX(), player.getY(), player.getZ());
        // 获取 mob 伤害类型的注册表项
        RegistryEntry<DamageType> mobDamageType = this.getWorld().getRegistryManager().get(RegistryKeys.DAMAGE_TYPE).getEntry(RegistryKey.of(RegistryKeys.DAMAGE_TYPE, new Identifier("smfs", "ghost"))).orElseThrow(() -> new IllegalStateException("MOB_ATTACK damage type not found"));
        // 创建伤害源
        DamageSource damageSource = new DamageSource(mobDamageType, this);
        player.addStatusEffect(new StatusEffectInstance(StatusEffects.WEAKNESS, 20, 1));

        player.damage(damageSource, 100.0f);
    }
}